﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Linq.Expressions;
using System.Globalization;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Text;

namespace CslData
{
    class Program
    {
        static void Main(string[] args)
        {
            int fromRound = 1;
            int toRound = 29;
            string roundInfoUrlTemplate = "http://www.csl-china.com/league/scheduleanddata?round={0}";
            List<MatchInfo> allMatches = new List<MatchInfo>();
            List<string> strList = new List<string>();
            List<Task> tasks = new List<Task>();
            for (int i = fromRound; i <= toRound; i++)
            {
                var k = i;//如果不加这句，会一直只下载第30轮的页面
                var task = Task.Factory.StartNew(() =>
                {

                    //Task.from
                    var str = Parsers.GetMatchInfosStringByActualUrl(String.Format(roundInfoUrlTemplate, k));
                    //Parsers.GetMatchInfosByJsonString(str);
                    //strList.Add(str);
                    lock (allMatches)
                    {
                        allMatches.AddRange(Parsers.GetMatchInfosByJsonString(str));
                    }

                });
                tasks.Add(task);
            }
            Task.WhenAll(tasks.ToArray()).Wait();
            Console.WriteLine(allMatches.Count);
            //allMatches.OrderBy(match => match.Match.DateTime.ToFileTime());
            allMatches = allMatches.OrderBy(match => match.Match.Audiences).ToList();
            allMatches.ForEach(m =>
            {
                var dt = m.Match.DateTime;
                Console.WriteLine($"{dt.Year,4}/{dt.Month,2}/{dt.Day,2} {dt.Hour,2}:{dt.Minute,2}:{dt.Second,2} {dt.DayOfWeek,10} " +
                    $"{m.Match.Round,2} {m.Match.HomeTeam,8} {m.Match.HomeScore,2}:" +
                    $"{m.Match.GuestScore,2} {m.Match.GuestTeam,8} {m.Match.Stadium,16}/{m.Match.Audiences}人");
            });
            Console.WriteLine();
            //var kvps = allMatches
            //          .GroupBy(m => m.Match.Stadium)
            //          .ToDictionary(g => g.Key, g => g.Sum(item => item.Match.Audiences));

            //kvps.ToList()
            //    .OrderBy(kvp => kvp.Value)
            //    .ToList()
            //    .ForEach(kvp => Console.WriteLine($"{kvp.Key} {kvp.Value}"));




            Console.ReadLine();
        }
    }

    public class Downloader
    {
        public string Url { get; set; }
        public int Limit { get; set; }
        public Downloader(string url, int limit)
        {
            Url = url;
            Limit = limit;
        }
        public bool Success { get; set; } = false;
        public Task<byte[]> DownloadData()
        {
            var result = new object();
            if (Limit >= 1)
            {
                var wc = new WebClient();
                var task = wc.DownloadDataTaskAsync(new Uri(this.Url));

                wc.DownloadDataCompleted += (a, b) =>
                {
                    if (b.Error == null)
                    {
                        Success = true;
                        result = task;
                        return;
                    }
                    else
                    {
                        Limit = Limit - 1;

                        task = DownloadData();
                        result = task;
                    }
                };
                //task.Wait();

                while (!Success)
                {

                }
                return result as Task<byte[]>;
            }
            else
            {
                throw new Exception("Download attempt times limit exceeded");
            }
        }


        public byte[] DD()
        {
            if (Limit >= 1)
            {
                var wc = new WebClient();
                wc.DownloadDataAsync(new Uri(Url));
                var result = new byte[0];
                wc.DownloadDataCompleted += (a, b) =>
                {
                    if (b.Error == null)
                    {
                        result = b.Result;
                    }
                    else
                    {
                        Limit -= 1;
                        result = DD();
                    }
                };
                while (result.Length == 0) { };


                result = Encoding.UTF8.GetBytes($"{Encoding.UTF8.GetString(result)}({Limit} times left.)");
                return result;
            }
            else
            {
                throw new NotImplementedException();
            }
        }
        public event DDFinallyFinished SuccessDownloaded;
        public delegate void DDFinallyFinished();
    }

    /// <summary>
    /// 比赛信息
    /// </summary>
    public class MatchInfo
    {
        [JsonProperty("match")]
        public Match Match { get; set; }
        [JsonProperty("events")]
        public List<Event> Events { get; set; }
    }


    public class Match
    {
        [JsonProperty("leagueMatchId")]
        public string MatchId { get; set; }
        [JsonProperty("videoUrl")]
        public string VideoUrl { get; set; }
        [JsonProperty("round")]
        public int Round { get; set; }
        [JsonProperty("homeClubName")]
        public string HomeTeam { get; set; }
        [JsonProperty("homeScore")]
        public int HomeScore { get; set; }
        [JsonProperty("guestClubName")]
        public string GuestTeam { get; set; }
        [JsonProperty("guestScore")]
        public int GuestScore { get; set; }
        [JsonProperty("stadium")]
        public string Stadium { get; set; }
        [JsonProperty("date")]
        public string Date { get; set; }
        [JsonProperty("time")]
        public string Time { get; set; }
        public DateTime DateTime
        {
            get
            {
                return DateTime.ParseExact(
                    $"{Date} {Time}",
                    "yyyy-MM-dd HH:mm",
                    CultureInfo.InvariantCulture
                );
            }
        }
        [JsonProperty("audiences")]
        public int Audiences { get; set; }
    }
    public class Event
    {
    }

}
